package com.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * properties工具类
 * 
 * @author root
 *
 */
public class PropertiesUtil {
	private static Logger log = Logger.getLogger(PropertiesUtil.class);

	public static String getKeyString(String propertiesFile, String key) {
		String res = null;
		try {
			// InputStream is =
			// PropertiesUtil.class.getClassLoader().getResourceAsStream(propertiesFile);
			InputStream is = new BufferedInputStream(new FileInputStream(getResource(propertiesFile)));
			Properties p = new Properties();
			p.load(is);
			res = p.getProperty(key);
		} catch (Exception err) {
			log.error("PropertiesUtil 获取 getKeyString 信息异常！");
		}
		return res;
	}

	/**
	 * 获取相对资源
	 * @param propertiesFile
	 * @return
	 */
	private static String getResource(String propertiesFile) {
		return System.getProperty("user.dir") + File.separator + "config" + File.separator + propertiesFile;
	}

	public static int getKeyInteger(String propertiesFile, String key) {
		int res = 0;
		try {
			InputStream is = new BufferedInputStream(new FileInputStream(getResource(propertiesFile)));
			Properties p = new Properties();
			p.load(is);
			res = Integer.parseInt(p.getProperty(key));
		} catch (Exception err) {
			log.error("PropertiesUtil 获取 getKeyInteger 信息异常！");
		}
		return res;
	}

	public static String getValueByKey(String propertiesFile, String key) {
		String res = null;
		try {
			InputStream is = new BufferedInputStream(new FileInputStream(getResource(propertiesFile)));
			Properties p = new Properties();
			p.load(is);
			is.close();
			res = p.getProperty(key);
		} catch (Exception err) {
			log.error("PropertiesUtil 获取 getValueByKey 信息异常！");
		}
		return res;
	}

	public static String setValueByKey(String propertiesFile, String key, String value) {
		String res = null;
		try {
			String newFilePath = PropertiesUtil.class.getResource("/").getPath();
			File file = new File(newFilePath);
			file = new File(newFilePath + propertiesFile);
			if (!file.exists())
				file.createNewFile();
			InputStream fis = new FileInputStream(file);
			Properties prop = new Properties();
			prop.load(fis);
			fis.close();

			prop.setProperty(key, value);
			OutputStream fos = new FileOutputStream(file.getPath());
			prop.store(fos, null);
			fos.close();
		} catch (Exception err) {
			err.printStackTrace();
		}

		return res;
	}
}
